﻿using System;
using System.Collections;
using System.Management;

namespace WMI
{
    public class Nic
    {
        public static ArrayList GetNicList()
        {
            ArrayList nicList = new ArrayList();

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["ipEnabled"])
                    nicList.Add(mo["Caption"]);
            }

            return nicList;
        }

        public static string[] GetDns(string nicName)
        {
            string[] dns = null;

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                if (mo["Caption"].Equals(nicName))
                {
                    dns = (string[])mo["DNSServerSearchOrder"];
                }
            }

            return dns;
        }

        public static void SetDns(string nicName, string dns, bool defined)
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();

            foreach (ManagementObject mo in moc)
            {
                if (mo["Caption"].Equals(nicName))
                {
                    ManagementBaseObject newDns =
                        mo.GetMethodParameters("SetDNSServerSearchOrder");

                    if (defined)
                        newDns["DNSServerSearchOrder"] = dns.Split(':');
                    else
                        newDns["DNSServerSearchOrder"] = null;

                    ManagementBaseObject setDns =
                        mo.InvokeMethod("SetDNSServerSearchOrder", newDns, null);

                    break;
                }
            }
        }
    }
}